// pages/myalbum/myalbum.js
let md5 = require("../../utils/md5.js")
let axios = require("../../utils/util.js")
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    albumList: [],
    image_addalbum: '',
    imgList:[],
  },
  shanchuAlbum(data) {
    let imgindex = data.currentTarget.dataset.picid
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&picId=" +
      this.data.albumList[imgindex].id +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      picId: this.data.albumList[imgindex].id,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    let _ = this;
    wx.showModal({
      title: '确认操作',
      content: '是否删除本张图片',
      success(res) {
        console.log(res);
        if (res.confirm) {
          axios.axios({
            url: "/user/delalbum",
            data: params
          }).then((res) => {
            // console.log(res.data.result),
              wx.showToast({
                title: res.data.text,
                icon: "none"
              })
            _.getAlbum()
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  tianjiaAlbum() {
    let _ = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res);
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        let timestamp = (Date.parse(new Date()) / 1000).toString();
        let data={
          userId: app.globalData.user_id,
          token: app.globalData.userToken,
          time: timestamp,
        }
        let _token = axios.encryption(data);
        let sign = md5.hexMD5(_token);
        wx.uploadFile({
          url: axios.testInterface + '/user/addalbum', //测试
          filePath: tempFilePaths[0],
          name: 'pic',
          formData: {
            userId: app.globalData.user_id,
            token:  app.globalData.userToken,
            time: timestamp,
            sign:sign,
          },
          success(res) {
            var data = res.data
            const strToObj = JSON.parse(data)
            _.setData({
              albumList: [..._.data.albumList, strToObj.result],
            })
            wx.showToast({
              title: '添加成功',
              icon: "none"
            })
          }
        })
      }
    })
  },
    // 放大背景图
    preview(event) {
      console.log(event.currentTarget.dataset.src);
      this.setData({
        imgList: []
      }) 
      this.data.albumList.forEach(item => {
        this.data.imgList.push(item.pic.toString());
      });
      let currentUrl = event.currentTarget.dataset.src
      wx.previewImage({
        current: currentUrl, // 当前显示图片的http链接
        urls: this.data.imgList // 需要预览的图片http链接列表
      })
    },
  myalbumClick() {
    // this.addalbum()
    wx.navigateBack({
      delta: 1,
    })
  },
  addalbum() {
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      pic: this.data.image_addalbum,
    };
    axios.axios({
      url: "/user/addalbum",
      data: params
    }).then((res) => {
      this.setData({
        albumList: res.data.result
      })
    })
  },
  // 长按保存功能
  saveImage (e) {
    const url = e.currentTarget.dataset.src;
    const { saveImage1, saveImage2, saveImage3, saveImage4 } = this
    saveImage1(url).then(saveImage2).then(saveImage3).then(saveImage4)
  },
  // 吊起 actionsheet
  saveImage1 (url) {
    const p1 = new Promise((resolve, reject) => {
      wx.showActionSheet({
        itemList: ['保存到相册'],
        success: res => {
          resolve(url)
        },
        fail: err => {
          reject(err)
        }
      })
    })
    return p1
  },
  // 授权
  saveImage2 (url) {
    const p2 = new Promise((resolve, reject) => {
      wx.getSetting({
        success: settings => {
          if (!settings.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                  // 同意授权
                  resolve(url)
              },
              fail: () => {
                  wx.showModal({
                      title: '保存失败',
                      content: '请开启访问手机相册权限',
                      success: () => {
                        wx.openSetting()
                      }
                  })
                  reject()
              }
            })
          } else {
            // 已经有权限了
            resolve(url)
          }
        }
      })
    })
    return p2
  },
  // 转换图片格式为本地路径
  saveImage3 (url) {
    const p3 = new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success: res => {
          resolve(res.path)
        },
        fail: () => {
          reject()
        }
      })
    })
    return p3
  },
  // 保存
  saveImage4 (path) {
    const p4 = new Promise((resolve, reject) => {
      wx.saveImageToPhotosAlbum({
        filePath: path,
        success: () => {
            wx.showToast({
               title: '已保存到相册',
            })
        },
        fail: err => {
          console.log(err)
        }
      })
    })
    return p4
  },
// saveImage (e) {
//   let _this = this
//   wx.showActionSheet({
//       itemList: ['保存到相册'],
//       success(res) {
//           let url = e.currentTarget.dataset.src;
//           wx.getSetting({
//               success: (res) => {
//                   if (!res.authSetting['scope.writePhotosAlbum']) {
//                       wx.authorize({
//                           scope: 'scope.writePhotosAlbum',
//                           success: () => {
//                               // 同意授权
//                               _this.saveImgInner(url);
//                           },
//                           fail: (res) => {
//                               console.log(res);
//                               wx.showModal({
//                                   title: '保存失败',
//                                   content: '请开启访问手机相册权限',
//                                   success(res) {
//                                       wx.openSetting()
//                                   }
//                               })
//                           }
//                       })
//                   } else {
//                       // 已经授权了
//                       _this.saveImgInner(url);
//                   }
//               },
//               fail: (res) => {
//                   console.log(res);
//               }
//           })   
//       },
//       fail(res) {
//           console.log(res.errMsg)
//       }
//   })
// },
// // 长按保存功能--保存部分
// saveImgInner (url) {
//   wx.getImageInfo({
//       src: url,
//       success: (res) => {
//           let path = res.path;
//           wx.saveImageToPhotosAlbum({
//               filePath: path,
//               success: (res) => {
//                   console.log(res);
//                   wx.showToast({
//                       title: '已保存到相册',
//                   })
//               },
//               fail: (res) => {
//                   console.log(res);
//               }
//           })
//       },
//       fail: (res) => {
//           console.log(res);
//       }
//   })
// },
  getAlbum() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/myAlbum",
      data: params
    }).then((res) => {
      console.log(res.data.result),
        this.setData({
          albumList: res.data.result
        })
        // this.addalbum()
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAlbum()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})